package com.ruoyi.location.domain.quickreport.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;

public class DateUtil {

    // 1. 定义日期格式
    public static final String FORMAT_YYYYMMDD = "yyyymmdd";
    public static final String FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
    public static final String FORMAT_YYYY_MM_DD_HH = "yyyy-MM-dd HH";
    public static final String FORMAT_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public static final String FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    // 2. 字符串格式转成Date
    public static Date parseDate(String dateStr, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new RuntimeException("Error parsing date: " + dateStr + " with format: " + format, e);
        }
    }

    // 3. Date转成字符串格式
    public static String formatDate(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    // 4. 日期比较大小
    public static int compareDates(Date date1, Date date2) {
        return date1.compareTo(date2);
    }

    // 5. 日期加n天，减n天
    public static Date addDays(Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, days);
        return calendar.getTime();
    }

    public static void main(String[] args) {
            // 测试字符串转Date
            Date date1 = parseDate("20231001", FORMAT_YYYYMMDD);
            System.out.println("Date from yyyymmdd: " + formatDate(date1, FORMAT_YYYY_MM_DD));

            // 测试Date转字符串
            Date date2 = new Date();
            System.out.println("Date to yyyy-MM-dd: " + formatDate(date2, FORMAT_YYYY_MM_DD));

            // 测试日期比较
            Date date3 = parseDate("2023-10-01", FORMAT_YYYY_MM_DD);
            Date date4 = parseDate("2023-11-01", FORMAT_YYYY_MM_DD);
            System.out.println("Compare date3 and date4: " + compareDates(date3, date4));

            // 测试日期加减天
            Date date5 = parseDate("2023-10-01", FORMAT_YYYY_MM_DD);
            Date date6 = addDays(date5, 10);
            System.out.println("Date after adding 10 days: " + formatDate(date6, FORMAT_YYYY_MM_DD));

            Date date7 = parseDate("2023-10-01", FORMAT_YYYY_MM_DD);
            Date date8 = addDays(date7, -5);
            System.out.println("Date after subtracting 5 days: " + formatDate(date8, FORMAT_YYYY_MM_DD));

    }
}